package com.tiyende.credit.loop.ui.activity

import android.annotation.SuppressLint
import android.app.PendingIntent
import android.graphics.Color
import android.text.Editable
import android.text.SpannableString
import android.text.Spanned
import android.text.TextWatcher
import android.text.style.ForegroundColorSpan
import android.text.style.UnderlineSpan
import android.view.View
import android.view.inputmethod.EditorInfo
import androidx.activity.result.IntentSenderRequest
import androidx.activity.result.contract.ActivityResultContracts
import com.google.android.gms.auth.api.identity.GetPhoneNumberHintIntentRequest
import com.google.android.gms.auth.api.identity.Identity
import com.tiyende.credit.loop.R
import com.tiyende.credit.loop.base.app.TiyendeActivityStackManager
import com.tiyende.credit.loop.common.CommonActivity
import com.tiyende.credit.loop.configs.TiyendeConfigs
import com.tiyende.credit.loop.databinding.TiyendeActivityLoginBinding
import com.tiyende.credit.loop.event.TiyendeEventPointType
import com.tiyende.credit.loop.ui.contract.IViewContract
import com.tiyende.credit.loop.ui.presenter.TiyendeLoginPresenter
import com.tiyende.credit.loop.utils.log.TiyendeLogger
import com.tiyende.credit.loop.utils.shared.TiyendeSharedHelper
import com.tiyende.credit.loop.utils.shared.TiyendeSharedKey
import com.tiyende.credit.loop.utils.track.TrackPointManager
import com.tiyende.credit.loop.weight.font.RobotoMediumEditText
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import org.json.JSONObject

/**
 * TiyendeCredit
 * @Author wwdeng
 * @CreateTime: 2024/11/11 16:48
 * @Annotation：登录
 */
class TiyendeLoginActivity: CommonActivity(), IViewContract.ITiyendeLoginView {
    lateinit var binding: TiyendeActivityLoginBinding
    private var presenter: TiyendeLoginPresenter? = null

    override fun getTiyendeRootView(): View {
        binding = TiyendeActivityLoginBinding.inflate(layoutInflater)
        return binding.root
    }

    override fun initTiyendeView() {
        setTiyendeTitleBarVisibility(View.VISIBLE)
        setTiyendeTextTitleVisibility(View.GONE)
        setTiyendeBackBtnVisibility(View.GONE)
        setTiyendeRightBtnRes(R.mipmap.tiyende_customer_white)
        //关闭所有页面
        TiyendeActivityStackManager.finishAllActivity(TiyendeLoginActivity::class.java)
        checkLoginBtnState()
    }

    override fun initTiyendeListener() {
        //客服
        rootViewBinding.rootCustomer.setOnClickListener {
            showCustomerDialog("Login Page")
            addEventPointRequestAction(TiyendeEventPointType.CLICK.TIYENDE_CLICK_CUSTOMER,"Login Page")
        }
        binding.textClickMobile.setOnClickListener {
            addEventPointRequestAction(TiyendeEventPointType.CLICK.TIYENDE_CLICK_USER_LOGIN_SELF_MOBILE)
            getTiyendeLoginSelfMobileAction()
        }
        binding.editMobile.setInputFocusChangeListener(object: RobotoMediumEditText.IInputFocusChangeListener {
            override fun onFocusChange(v: View?, hasFocus: Boolean) {

            }
            override fun onCompleteAction(v: View?, remark: String?) {
                addEventPointRequestAction(TiyendeEventPointType.FORM.TIYENDE_FORM_LOGIN_MOBILE, remark)
            }
        })
        //电话号码入框监听
        binding.editMobile.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
            }
            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
            }
            override fun afterTextChanged(s: Editable?) {
                if (getTiyendeLoginMobile().isNotEmpty()){
                    binding.editMobile.setTextColor(Color.parseColor("#FFFFFFFF"))
                    binding.textLoginZoneCode.setTextColor(Color.parseColor("#FFFFFFFF"))
                } else {
                    binding.editMobile.setTextColor(Color.parseColor("#FFCBD5E1"))
                    binding.textLoginZoneCode.setTextColor(Color.parseColor("#FFCBD5E1"))
                }
                checkLoginBtnState()
            }
        })
        binding.editMobile.setOnEditorActionListener { v, actionId, event ->
            if (actionId == EditorInfo.IME_ACTION_DONE) {
                binding.editMobile.clearFocus()
                true
            }
            false
        }

        //隐私政策切换
        binding.loginPPCheckBox.setOnCheckedChangeListener { _, isChecked ->
            checkLoginBtnState()
            when (isChecked) {
                true -> {
                    addEventPointRequestAction(TiyendeEventPointType.CLICK.TIYENDE_CLICK_LOGIN_PRIVACY_AGREE)
                }
                false -> {
                    addEventPointRequestAction(TiyendeEventPointType.CLICK.TIYENDE_CLICK_LOGIN_PRIVACY_DENY)
                }
            }
        }

        //登录
        binding.btnLogin.setOnClickListener {
            binding.editMobile.clearFocus()
            addEventPointRequestAction(TiyendeEventPointType.CLICK.TIYENDE_CLICK_LOGIN_NEXT,getTiyendeLoginMobile())
            onHideSoftInput(binding.editMobile)
            // TODO: 首页点 Withdraw Now 上报所有埋点
            TrackPointManager.getInstance().manualReport()
            presenter?.requestUserLoginAction()
        }

        //隐私协议
        binding.textLoginPrivacyPolicy.setOnClickListener {
            val showTitle = getString(R.string.tiyende_privacy_policy_title)
            val linkUrl = TiyendeConfigs.TIYENDE_PRIVACY_POLICY_LINK
            TiyendeWebviewActivity.start(this,showTitle, linkUrl)
        }
    }

    @SuppressLint("SetTextI18n")
    override fun loadTiyendeData() {
        if (presenter == null){
            presenter = TiyendeLoginPresenter(this)
        }
        binding.textLoginZoneCode.text = "+${TiyendeSharedHelper.queryTiyendeSharedString(TiyendeSharedKey.TIYENDE_TIMEZONE_CODE)}"
        binding.txtSignIn.text = String.format(getString(R.string.tiyende_login_sign_in_to),getString(R.string.app_name))

        val showText = String.format(getString(R.string.tiyende_login_privacy_policy),getString(R.string.tiyende_privacy_policy_title))
        val spString = SpannableString(showText)
        val start = showText.indexOf(getString(R.string.tiyende_privacy_policy_title))
        spString.setSpan(ForegroundColorSpan(Color.parseColor("#FFFFFFFF")), start, showText.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
        //添加下划线
        spString.setSpan(UnderlineSpan(), start, showText.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
        binding.textLoginPrivacyPolicy.text = spString
    }

    /**
     * 设置登录按钮状态
     */
    private fun checkLoginBtnState() {
        binding.loginErrorLayout.visibility = View.INVISIBLE
        binding.loginMobileLayout.shapeDrawableBuilder
            .setSolidColor(Color.parseColor("#FF1F2937"))
            .setStrokeColor(Color.parseColor("#FF334155"))
            .setStrokeSize(resources.getDimension(com.lib.common.R.dimen.dp_1).toInt())
            .intoBackground()
        if (binding.loginPPCheckBox.isChecked && getTiyendeLoginMobile().isNotEmpty()) {
            binding.btnLogin.isEnabled = true
        } else {
            binding.btnLogin.isEnabled = false
        }
    }

    /**
     * 获取电话号码
     */
    override fun getTiyendeLoginMobile(): String {
        return binding.editMobile.text.toString().trim()
    }

    override fun showTiyendeLoginFailure(data: JSONObject) {
        binding.loginErrorLayout.visibility = View.VISIBLE
        binding.loginMobileLayout.shapeDrawableBuilder
            .setSolidColor(Color.parseColor("#FF1F2937"))
            .setStrokeColor(Color.parseColor("#FFF36767"))
            .setStrokeSize(resources.getDimension(com.lib.common.R.dimen.dp_2).toInt())
            .intoBackground()
    }

    override fun showTiyendeLoginMainPage() {
        onIntent(TiyendeMainActivity::class.java)
        finish()
    }

    /**
     * 获取本机手机号码
     */
    private fun getTiyendeLoginSelfMobileAction(){
        val request: GetPhoneNumberHintIntentRequest = GetPhoneNumberHintIntentRequest.builder().build()
        Identity.getSignInClient(this)
            .getPhoneNumberHintIntent(request)
            .addOnSuccessListener { result: PendingIntent ->
                try {
                    phoneNumberHintIntentResultLauncher.launch(IntentSenderRequest.Builder(result).build())
                } catch (e: Exception) {
                    TiyendeLogger.e("Launching the PendingIntent failed")
                    showTiyendeLoginEditMobile()
                }
            }
            .addOnFailureListener {
                TiyendeLogger.e("Phone Number Hint failed : OnFailureListener")
                showTiyendeLoginEditMobile()
            }
    }

    private val phoneNumberHintIntentResultLauncher = registerForActivityResult(
        ActivityResultContracts.StartIntentSenderForResult()) { result ->
        try {
            var phoneNumber = Identity.getSignInClient(this).getPhoneNumberFromIntent(result.data)
            TiyendeLogger.e(">>>>>>>>>>>>>>>>>>>>>>>Phone Number $phoneNumber")
            addEventPointRequestAction(TiyendeEventPointType.FORM.TIYENDE_FORM_USER_LOGIN_SELF_MOBILE,phoneNumber)
            //时区区号
            val zoneCode = "+${TiyendeSharedHelper.queryTiyendeSharedString(TiyendeSharedKey.TIYENDE_TIMEZONE_CODE)}"
            phoneNumber = phoneNumber.replace(zoneCode,"")
            binding.editMobile.setText(phoneNumber)
            binding.editMobile.visibility = View.VISIBLE
            binding.textClickMobile.visibility = View.GONE
            binding.editMobile.requestFocus()
            binding.editMobile.setSelection(getTiyendeLoginMobile().length)
        } catch(e: Exception) {
            TiyendeLogger.e("Phone Number Hint failed：${e.message}")
            addEventPointRequestAction(TiyendeEventPointType.CLICK.TIYENDE_CLICK_USER_LOGIN_SELF_MOBILE_CANCEL,e.message)
            showTiyendeLoginEditMobile()
        }
    }

    /**
     * 显示手机号码输入框
     */
    private fun showTiyendeLoginEditMobile(){
        binding.editMobile.visibility = View.VISIBLE
        binding.textClickMobile.visibility = View.GONE

        launch(Dispatchers.Main){
            delay(200)
            binding.editMobile.requestFocus()
            onShowSoftInput(binding.editMobile)
            binding.editMobile.setSelection(getTiyendeLoginMobile().length) // 将光标设置到文本末尾
        }
    }

    override fun onStart() {
        super.onStart()
        addEventPointRequestAction(TiyendeEventPointType.PAGE.TIYENDE_PAGE_LOGIN_START)
    }

    override fun onDestroy() {
        super.onDestroy()
        addEventPointRequestAction(TiyendeEventPointType.PAGE.TIYENDE_PAGE_LOGIN_END)
    }
}